﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace BoAddonBiz_FreightForwarder
{
    public class B1Form_OrderNumber : SAPBoAddon.B1Form
    {
        protected override bool BeforeSaveCheckFormData()
        {
            return true;
        }

        protected override void FormEditModeChange(SAPBoAddon.frmItemEditMode frmEditMode)
        {

        }

        protected override void FormInfoSetting(SAPBoAddon.B1FormSetting FormSetting)
        {
            FormSetting.FormType = "AVA_FF_OrderNumber";
            FormSetting.FormFileName = FormType + "Form.srf";
        }

        protected override void InitializeForm(SAPBoAddon.B1FormInitializePar InitPar)
        {
            SAPbouiCOM.Matrix oMtx;
            SAPbobsCOM.Recordset ors;
            SAPbouiCOM.DBDataSource dbds;

            dbds = CurrentForm.DataSources.DBDataSources.Item("@AVA_FF_ONNM");
            oMtx = CurrentForm.Items.Item("mtx_0").Specific;
            ors = SBOCompany.GetBusinessObject(SAPbobsCOM.BoObjectTypes.BoRecordset);
            dbds.Clear();
            ors.DoQuery(@"SELECT ISNULL(T1.DocEntry,(ROW_NUMBER() over( order by t1.docentry desc))+(SELECT MAX(Cast(Code as int)) FROM [@AVA_FF_ONNM])) DocEntry,
	                        Case When ISNULL(U_ObjectCode,'') = '' then T0.Code else U_ObjectCode End U_ObjectCode,
	                        Case When ISNULL(U_ObjectName,'') = '' then T0.Name else U_ObjectName End U_ObjectName,U_IsAutokey,U_Length
                        FROM OUDO T0
	                        FULL JOIN [@AVA_FF_ONNM] T1 ON t0.Code = T1.U_ObjectCode
                        Where T0.[TYPE] = '3'
                             And Not T0.Code IN (
                                'AVA_FF_OrderNumber',
                                'AVA_FF_Inventory',
                                'AVA_FF_GoodsReceipt',
                                'AVA_FF_GoodsIssue',
                                'AVA_FF_AirLine',
                                'AVA_FF_AirLine',
                                'AVA_FF_AffixUpload',
                                'AVA_Control',
                                'AVA_AU_TARGET',
                                'AVA_ApprovalTem',
                                'AVA_ApprovalStep',
                                'AVA_ApprovalStages')
                        Order By DocEntry ");
            for (int i = 0; i < ors.RecordCount; i++)
            {
                dbds.InsertRecord(i);
                dbds.SetValue("DocEntry", i, ors.Fields.Item("DocEntry").Value);
                dbds.SetValue("U_ObjectCode", i, ors.Fields.Item("U_ObjectCode").Value);
                dbds.SetValue("U_ObjectName", i, ors.Fields.Item("U_ObjectName").Value);
                dbds.SetValue("U_IsAutokey", i, ors.Fields.Item("U_IsAutokey").Value);
                dbds.SetValue("U_Length", i, ors.Fields.Item("U_Length").Value);
                ors.MoveNext();
            }
            oMtx.LoadFromDataSourceEx();
            oMtx.AutoResizeColumns();
        }

        public B1Form_OrderNumber()
        {
            this.frm_ItemEvent += new SAPBoAddon.IB1FormEvents.B1ItemEventEventHandler(B1Form_OrderNumber_frm_ItemEvent);
        }

        void B1Form_OrderNumber_frm_ItemEvent(SAPBoAddon.B1AddonBase.B1ItemEvent pVal, ref bool BubbleEvent)
        {
            if (!pVal.BeforeAction)
            {
                if (pVal.EventType == SAPbouiCOM.BoEventTypes.et_FORM_CLOSE)
                {
                    if (CurrentForm.DataSources.UserDataSources.Item("FormMode").Value == "UPDATE")
                    {
                        if (SBOApp.MessageBox("数据没有保存，是否保存？", 1, "是", "否") == 1)
                        {
                            Save();
                        }
                    }
                }
                if (pVal.ItemUID == "5" && pVal.EventType == SAPbouiCOM.BoEventTypes.et_ITEM_PRESSED)
                {
                    CurrentForm.Close();
                }
                if (pVal.ItemUID == "mtx_0" && pVal.ItemChanged)
                {
                    if (string.IsNullOrEmpty(CurrentForm.DataSources.UserDataSources.Item("FormMode").Value) || CurrentForm.DataSources.UserDataSources.Item("FormMode").Value == "OK")
                    {
                        CurrentForm.DataSources.UserDataSources.Item("FormMode").Value = "UPDATE";
                        CurrentForm.Items.Item("4").Specific.caption = "更新";
                    }
                }
                if (pVal.ItemUID == "4" && pVal.EventType == SAPbouiCOM.BoEventTypes.et_ITEM_PRESSED)
                {
                    if (CurrentForm.DataSources.UserDataSources.Item("FormMode").Value == "UPDATE")
                    {
                        Save();
                        CurrentForm.DataSources.UserDataSources.Item("FormMode").Value = "OK";
                        CurrentForm.Items.Item("4").Specific.caption = "确定";
                    }
                    else
                    {
                        CurrentForm.Close();
                    }
                }
                if (pVal.ItemUID == "mtx_0" && pVal.Row > 0 && pVal.EventType == SAPbouiCOM.BoEventTypes.et_DOUBLE_CLICK)
                {
                    OpenChildForm(pVal.Row);
                }
            }
        }
        /// <summary>
        /// 保存数据
        /// </summary>
        private void Save()
        {
            SAPbobsCOM.Recordset ors;
            SAPbouiCOM.Matrix oMtx;
            SAPbouiCOM.DBDataSource dbds;
            string SQL_Check = string.Empty;
            try
            {
                oMtx = CurrentForm.Items.Item("mtx_0").Specific;
                dbds = CurrentForm.DataSources.DBDataSources.Item("@AVA_FF_ONNM");
                ors = SBOCompany.GetBusinessObject(SAPbobsCOM.BoObjectTypes.BoRecordset);

                oMtx.FlushToDataSource();
                if (SBOCompany.InTransaction == false) SBOCompany.StartTransaction();
                for (int i = 0; i < dbds.Size; i++)
                {
                    SQL_Check=string.Format("SELECT COUNT(1) FROM [@AVA_FF_ONNM] Where U_ObjectCode =N'{0}' ",dbds.GetValue("U_ObjectCode", i).ToString().Trim());
                    ors.DoQuery(SQL_Check);
                    if (ors.Fields.Item(0).Value > 0)
                    {
                        ors.DoQuery("UPDATE [@AVA_FF_ONNM] SET U_IsAutoKey = '" 
                            + dbds.GetValue("U_IsAutoKey", i).ToString().Trim()
                            + "' ,U_Length = " + dbds.GetValue("U_Length", i).ToString().Trim()
                            + " Where U_ObjectCode = '" + dbds.GetValue("U_ObjectCode", i).ToString().Trim()
                            + "'");
                    }
                    else
                    {
                        string SQL = "INSERT INTO [@AVA_FF_ONNM] (Code,Name,DocEntry,U_ObjectCode,U_ObjectName,U_IsAutokey,U_Length) Values ('" +
                            dbds.GetValue("DocEntry", i).ToString().Trim() + "','" +
                            dbds.GetValue("DocEntry", i).ToString().Trim() + "','" +
                            dbds.GetValue("DocEntry", i).ToString().Trim() + "','" +
                            dbds.GetValue("U_ObjectCode", i).ToString().Trim() + "','" +
                            dbds.GetValue("U_ObjectName", i).ToString().Trim() + "','" +
                            dbds.GetValue("U_IsAutoKey", i).ToString().Trim() + "'," +
                            ((string.IsNullOrEmpty(dbds.GetValue("U_Length", i).ToString().Trim()) || dbds.GetValue("U_Length", i).ToString().Trim() == "") ? "0" : dbds.GetValue("U_Length", i).Trim()) + ")";
                        ors.DoQuery(SQL);
                        ors.DoQuery("UPDate ONNM SET AutoKey = " + dbds.GetValue("DocEntry", i).Trim() + " Where ObjectCode = 'AVA_FF_OrderNumber'");
                    }
                }
                if (SBOCompany.InTransaction) SBOCompany.EndTransaction(SAPbobsCOM.BoWfTransOpt.wf_Commit);
            }
            catch (Exception ex)
            {
                if (SBOCompany.InTransaction) SBOCompany.EndTransaction(SAPbobsCOM.BoWfTransOpt.wf_RollBack);
                throw (ex);
            }
        }
        private void OpenChildForm(int row)
        {
            SAPbouiCOM.Form oParentForm;
            SAPbouiCOM.Form oChildForm;
            SAPbouiCOM.Matrix oMtx;

            oParentForm = CurrentForm;
            oMtx = oParentForm.Items.Item("mtx_0").Specific;
            oMtx.SelectRow(row, true, false);
            oChildForm = SAPBoAddon.B1Assistant.Form.LoadToSBOApplciation(System.Windows.Forms.Application.StartupPath + @"\Form\AVA_FF_NumberRuleForm.srf", "", true);
            #region 设置主了窗体UID
            oParentForm.DataSources.UserDataSources.Item("ChildUID").Value = oChildForm.UniqueID;
            oChildForm.DataSources.UserDataSources.Item("ParentUID").Value = oParentForm.UniqueID;
            #endregion
            oChildForm.DataSources.UserDataSources.Item("Code").Value = SAPBoAddon.B1Assistant.Matrix.GetCellValue(oMtx, "col_f", row).ToString();
            oChildForm.DataSources.UserDataSources.Item("ObjectName").Value = SAPBoAddon.B1Assistant.Matrix.GetCellValue(oMtx, "col_2", row).ToString();
            oChildForm.DataSources.UserDataSources.Item("Length").Value = SAPBoAddon.B1Assistant.Matrix.GetCellValue(oMtx, "col_4", row).ToString();
            ChildOp(oChildForm);
        }
        private void ChildOp(SAPbouiCOM.Form oForm)
        {
            SAPbouiCOM.Matrix oMtx;
            SAPbobsCOM.Recordset ors;
            SAPbouiCOM.DBDataSource dbds;

            dbds = oForm.DataSources.DBDataSources.Item("@AVA_FF_NNM1");
            oMtx = oForm.Items.Item("mtx_0").Specific;
            ors = SBOCompany.GetBusinessObject(SAPbobsCOM.BoObjectTypes.BoRecordset);
            dbds.Clear();
            ors.DoQuery(@"select Lineid,U_StartsWith,U_EndsWith,U_CharType,U_AlterType,U_Reset,U_Chars from [@AVA_FF_NNM1] Where Code = '" + oForm.DataSources.UserDataSources.Item("Code").Value.Trim() + "'");
            for (int i = 0; i < ors.RecordCount; i++)
            {
                dbds.InsertRecord(i);
                dbds.SetValue("LineId", i, ors.Fields.Item("LineId").Value);
                dbds.SetValue("U_StartsWith", i, ors.Fields.Item("U_StartsWith").Value);
                dbds.SetValue("U_EndsWith", i, ors.Fields.Item("U_EndsWith").Value);
                dbds.SetValue("U_CharType", i, ors.Fields.Item("U_CharType").Value);
                dbds.SetValue("U_AlterType", i, ors.Fields.Item("U_AlterType").Value);
                dbds.SetValue("U_Reset", i, ors.Fields.Item("U_Reset").Value);
                dbds.SetValue("U_Chars", i, ors.Fields.Item("U_Chars").Value);
                ors.MoveNext();
            }
            oMtx.LoadFromDataSourceEx();
            oMtx.AutoResizeColumns();
        }
    }

    public class B1Form_NumberRule : SAPBoAddon.B1Form
    {

        protected override bool BeforeSaveCheckFormData()
        {
            return true;
        }

        protected override void FormEditModeChange(SAPBoAddon.frmItemEditMode frmEditMode)
        {
        }

        protected override void FormInfoSetting(SAPBoAddon.B1FormSetting FormSetting)
        {
            FormSetting.FormType = B1FormTypes.ado_AVA_FF_NumberRule;
            FormSetting.FormFileName = B1FormTypes.ado_AVA_FF_NumberRule + "Form.srf";

            FormSetting.MatrixSetting.MtxUID = "mtx_0";
            FormSetting.MatrixSetting.NotAllowNoLineSave = false;
            FormSetting.MatrixSetting.AutoAddNewLine = true;
            FormSetting.MatrixSetting.AutoLineKeyCol = "col_f";
            FormSetting.MatrixSetting.TableName = "@AVA_FF_NNM1";
            FormSetting.MatrixSetting.TableKeyField = "LineId";
            FormSetting.MatrixSetting.TableVisOrder = "LineId";
            FormSetting.MatrixSetting.AffectsFormModeAddRow = true;
            FormSetting.MatrixSetting.PrimaryLineCol = "col_f";
            FormSetting.MatrixSetting.addButtonUID = "add";
            FormSetting.MatrixSetting.delButtonUID = "del";
            FormSetting.MatrixSetting.Add();
        }

        protected override void InitializeForm(SAPBoAddon.B1FormInitializePar InitPar)
        {

        }
        public B1Form_NumberRule()
        {
            this.frm_ItemEvent += new SAPBoAddon.IB1FormEvents.B1ItemEventEventHandler(B1Form_NumberRule_frm_ItemEvent);
        }

        void B1Form_NumberRule_frm_ItemEvent(SAPBoAddon.B1AddonBase.B1ItemEvent pVal, ref bool BubbleEvent)
        {
            if (pVal.BeforeAction)
            { }
            else
            {
                if ((pVal.ItemUID == "add" || pVal.ItemUID == "del") && pVal.EventType == SAPbouiCOM.BoEventTypes.et_ITEM_PRESSED)
                {
                    CurrentForm.DataSources.UserDataSources.Item("FormMode").Value = "UPDATE";
                    CurrentForm.Items.Item("ok").Specific.caption = "更新";
                }
                if (pVal.EventType == SAPbouiCOM.BoEventTypes.et_FORM_CLOSE)
                {
                    if (CurrentForm.DataSources.UserDataSources.Item("FormMode").Value == "UPDATE")
                    {
                        if (SBOApp.MessageBox("数据没有保存，是否保存？", 1, "是", "否") == 1)
                        {
                            Save();
                        }
                    }
                }
                if (pVal.ItemUID == "mtx_0" && pVal.ItemChanged)
                {
                    if (string.IsNullOrEmpty(CurrentForm.DataSources.UserDataSources.Item("FormMode").Value) || CurrentForm.DataSources.UserDataSources.Item("FormMode").Value == "OK")
                    {
                        CurrentForm.DataSources.UserDataSources.Item("FormMode").Value = "UPDATE";
                        CurrentForm.Items.Item("ok").Specific.caption = "更新";
                    }
                }
                if (pVal.ItemUID == "ok" && pVal.EventType == SAPbouiCOM.BoEventTypes.et_ITEM_PRESSED)
                {
                    if (CurrentForm.DataSources.UserDataSources.Item("FormMode").Value == "UPDATE")
                    {
                        Save();
                        CurrentForm.DataSources.UserDataSources.Item("FormMode").Value = "OK";
                        CurrentForm.Items.Item("ok").Specific.caption = "确定";
                    }
                    else
                    {
                        CurrentForm.Close();
                    }
                }
                if (pVal.ItemUID == "cancel" && pVal.EventType == SAPbouiCOM.BoEventTypes.et_ITEM_PRESSED)
                {
                    CurrentForm.Close();
                }
            }
        }
        /// <summary>
        /// 
        /// </summary>
        private void Save()
        {
            SAPbobsCOM.Recordset ors;
            SAPbouiCOM.Matrix oMtx;
            SAPbouiCOM.DBDataSource dbds;
            try
            {
                oMtx = CurrentForm.Items.Item("mtx_0").Specific;
                dbds = CurrentForm.DataSources.DBDataSources.Item("@AVA_FF_NNM1");
                ors = SBOCompany.GetBusinessObject(SAPbobsCOM.BoObjectTypes.BoRecordset);

                oMtx.FlushToDataSource();
                if (SBOCompany.InTransaction == false) SBOCompany.StartTransaction();

                if (oMtx.RowCount <= 0)
                {
                    ors.DoQuery("Delete FROM [@AVA_FF_NNM1] Where Code = '" + CurrentForm.DataSources.UserDataSources.Item("Code").Value.Trim() + "'");
                    if (SBOCompany.InTransaction) SBOCompany.EndTransaction(SAPbobsCOM.BoWfTransOpt.wf_Commit);
                    return;
                }
                string SQL = string.Empty;
                if (SBOApp.MessageBox("编码规则发生变化是否重新编码？\r\n如果编码规则发生变化而没有重新编码，可能会影响单据的编码生成。", 1, "是", "否") == 1)
                {
                    SQL = "UPDATE [@AVA_FF_ONNM] SET U_Currentkey=null Where Code = '" + CurrentForm.DataSources.UserDataSources.Item("Code").Value.Trim() + "'";
                    ors.DoQuery(SQL);
                }
                for (int i = 0; i < dbds.Size; i++)
                {
                    //先删除对应的数据
                    dbds.SetValue("Code", i, CurrentForm.DataSources.UserDataSources.Item("Code").Value.Trim());
                    SQL = SAPBoAddon.B1Assistant.DBDataSource.ReturnDeleteSQL(dbds, i, new string[] { "Code", "LineId" });
                    ors.DoQuery(SQL);
                    //插入新的数据
                    SQL = SAPBoAddon.B1Assistant.DBDataSource.ReturnInsertSQL(dbds, i);
                    ors.DoQuery(SQL);
                }
                if (SBOCompany.InTransaction) SBOCompany.EndTransaction(SAPbobsCOM.BoWfTransOpt.wf_Commit);
            }
            catch (Exception ex)
            {
                if (SBOCompany.InTransaction) SBOCompany.EndTransaction(SAPbobsCOM.BoWfTransOpt.wf_RollBack);
                throw (ex);
            }
        }
    }
}